//
//  Token.m
//  TabulaImaginarius2
//
//  Created by TA2 on 5/23/11.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "Token.h"


@implementation Token
@synthesize tokenImagePath;
@synthesize tiledImages;
@synthesize startingMoveCoordinate;
@synthesize tokenId;
@synthesize protocolId;

+ (NSArray *)tileImage:(UIImage *)image
			 withWidth:(int)width
			withHeight:(int)height {
	CGImageRef fullImage = [image CGImage];
	NSMutableArray *images = [[[NSMutableArray alloc] init] autorelease];
  
	
	CGSize tileSize = CGSizeMake(image.size.width/width, image.size.height/height);
	for (int x = 0; x < width; x++) {
		[images addObject:[[[NSMutableArray alloc] init] autorelease]];
		for (int y = 0; y < height; y++) {
			CGPoint origin = CGPointMake(tileSize.width * x, tileSize.height * y);
			CGImageRef tileImage = CGImageCreateWithImageInRect(fullImage, (CGRect){origin, tileSize});
			UIImage *image = [UIImage imageWithCGImage:tileImage];
			UIGraphicsBeginImageContext((CGSize){75.0f, 75.0f});
			CGLayerRef imageLayer = CGLayerCreateWithContext(UIGraphicsGetCurrentContext(), image.size, NULL);
			UIGraphicsEndImageContext();
			UIGraphicsPushContext(CGLayerGetContext(imageLayer));
			[image drawInRect:(CGRect){(CGPoint){0, 0}, image.size}];
			UIGraphicsPopContext();
			[[images objectAtIndex:x] addObject:(NSObject *)imageLayer];
            CFRelease(tileImage);
            CFRelease(imageLayer);
		}
	}
	return images;
}

- (id)initWithImageArray:(NSArray *)images withId:(NSString *) identifier {
	tokenId = [[NSString stringWithString:identifier] retain];
	tiledImages = [images retain];
    
    UIGraphicsBeginImageContext((CGSize){75.0, 75.0});
    idLayer = CGLayerCreateWithContext(UIGraphicsGetCurrentContext(), (CGSize){75.0, 75.0}, NULL);
    UIGraphicsEndImageContext();
    
    UIGraphicsBeginImageContext((CGSize){75.0, 75.0});
    CGContextSetTextDrawingMode(UIGraphicsGetCurrentContext(), kCGTextFillStrokeClip);
    CGContextSetFillColorWithColor(UIGraphicsGetCurrentContext(), [[UIColor whiteColor] CGColor]);
    CGContextSetStrokeColorWithColor(UIGraphicsGetCurrentContext(), [[UIColor grayColor] CGColor]);
    CGContextSetShouldSmoothFonts(UIGraphicsGetCurrentContext(), YES);
    if ([[tokenId componentsSeparatedByString:@"§"].lastObject length] > 2) {
        [[tokenId componentsSeparatedByString:@"§"].lastObject drawInRect:CGRectMake(45.0f, 55.0f, 75.0, 75.0) withFont:[UIFont fontWithName:@"ArialRoundedMTBold" size:16.0f]];

    } else if ([[tokenId componentsSeparatedByString:@"§"].lastObject length] > 1) {
        [[tokenId componentsSeparatedByString:@"§"].lastObject drawInRect:CGRectMake(55.0f, 55.0f, 75.0, 75.0) withFont:[UIFont fontWithName:@"ArialRoundedMTBold" size:16.0f]];

    } else {
        [[tokenId componentsSeparatedByString:@"§"].lastObject drawInRect:CGRectMake(60.0f, 55.0f, 75.0, 75.0) withFont:[UIFont fontWithName:@"ArialRoundedMTBold" size:16.0f]];
    }
       UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
	UIGraphicsEndImageContext();
    
    UIGraphicsPushContext(CGLayerGetContext(idLayer));
    [image drawInRect:CGRectMake(0.0f, 0.0f, 75.0, 75.0)];
    UIGraphicsPopContext();
	return self;
}

- (void)dealloc {
    [tokenImagePath release];
    tokenImagePath = nil;
    [tokenId release];
    tokenId = nil;
    [tiledImages release];
    tiledImages = nil;
    [originLock release];
    originLock = nil;
    [protocolId release];
    protocolId = nil;
    if (idLayer) {
        CGLayerRelease(idLayer);
        idLayer = nil;
    }
    [super dealloc];
}

- (void)rotateClockwise {
	
}

- (void)rotateCounterClockwise {
	
}

- (CGLayerRef)getImageAtPoint:(CGPoint)point withOffset:(int)offset {
	if (offset > 0) {
		if ((int)(point.x - origin.x) >= [tiledImages count]) {
			int offsetX = (int)(point.x - origin.x) - ([tiledImages count] - 1);
			if (offsetX <= offset) {
				point.x = point.x - offsetX;
			}
		} else if ((int)(point.x - origin.x) < 0) {
			if (offset <= ((int)(point.x - origin.x) * -1)) {
				point.x = origin.x;
			}
		}
		if ((int)(point.y - origin.y) >= [((NSMutableArray *)[tiledImages objectAtIndex:0]) count]) {
			int offsetY = (int)(point.y - origin.y) - ([((NSMutableArray *)[tiledImages objectAtIndex:0]) count] - 1);
			if (offsetY <= offset) {
				point.y = point.y - offsetY;
			}
		} else if ((int)(point.y - origin.y) < 0) {
			if (offset <= ((int)(point.y - origin.y) * -1)) {
				point.y = origin.y;
			}
		}
	}
	if ([tiledImages count] > (int)(point.x - origin.x)) {
		if ([((NSMutableArray *)[tiledImages objectAtIndex:0]) count] > (int)(point.y - origin.y)) {
			return (CGLayerRef)([((NSMutableArray *)[tiledImages objectAtIndex:(int)(point.x - origin.x)]) objectAtIndex:(int)(point.y - origin.y)]);
		}
	}
	return nil;
}

- (CGLayerRef)getIdLayerAtPoint:(CGPoint) point {
    if ([protocolId isEqualToString:@"TP"]) {
        if ([tiledImages count] - 1 == point.x - origin.x) {
            if ([[tiledImages objectAtIndex:point.x - origin.x] count] - 1 == point.y - origin.y) {
                return idLayer;
            }
        }
    }
    return nil;
}

- (NSMutableArray *)getPointsWithOffset:(int)offset {
	NSMutableArray *points = [[[NSMutableArray alloc] init] autorelease];
	int startX = origin.x - offset;
	int endX = origin.x + [tiledImages count] + offset;
	int startY = origin.y - offset;
	int endY = origin.y + [((NSMutableArray *)[tiledImages objectAtIndex:0]) count] + offset;
	for (int k = startX; k < endX; k++) {
		for (int i = startY; i < endY; i++) {
			[points addObject:[NSValue valueWithCGPoint:(CGPoint) {k, i}]];
		}
	}
	return points;
}

- (void)setOrigin:(CGPoint)point {
	@synchronized(originLock){
		origin = (CGPoint){point.x + movementOffset.x, point.y + movementOffset.y};
	}
}

- (void)setPoint:(CGPoint)point { 	
    @synchronized(originLock){
		coordPoint = point;
	}
}

- (CGPoint)getOrigin {
	@synchronized(originLock) {
		return CGPointMake(origin.x, origin.y);
	}	
}

- (CGPoint)getPoint {
	@synchronized(originLock) {
		return CGPointMake(coordPoint.x, coordPoint.y);
	}	
}

- (void)setImageArray:(NSArray *)images {
	[tiledImages release];
	tiledImages = images;
}

- (void)enterMovingMode:(CGPoint)startingCoordinate {
	self.startingMoveCoordinate = startingCoordinate;
	movementOffset = (CGPoint){origin.x - startingCoordinate.x, origin.y - startingCoordinate.y};
}

- (void)leaveMovingMode {
	movementOffset = (CGPoint){0, 0};
}

- (void)encodeWithCoder:(NSCoder *)coder {
    [coder encodeObject:tokenImagePath forKey:@"tokenImagePath"];
    [coder encodeObject:tokenId forKey:@"tokenId"];
    [coder encodeCGPoint:origin forKey:@"tokenOrigin"];
    [coder encodeCGPoint:coordPoint forKey:@"tokenCoordinate"];
    [coder encodeObject:protocolId forKey:@"protocolId"];
}
//TODO fix idlayer
- (id)initWithCoder:(NSCoder *)coder {
    self = [super init];
    tokenImagePath = [[coder decodeObjectForKey:@"tokenImagePath"] retain];
    tiledImages = [[[LoadedImages sharedLoadedImages].tiledTokenImages objectForKey:tokenImagePath] retain];
    if (!tiledImages) {
        UIImage *image = [[LoadedImages sharedLoadedImages].images objectForKey:tokenImagePath];
        NSArray *arguments = [tokenImagePath componentsSeparatedByCharactersInSet:
                              [NSCharacterSet characterSetWithCharactersInString:@"_"]];
        tiledImages = [[Token tileImage:image withWidth:[[arguments objectAtIndex:[arguments count] -1] intValue] withHeight:[[[arguments objectAtIndex:[arguments count] -2] stringByDeletingPathExtension] intValue]] retain];
        [[LoadedImages sharedLoadedImages].tiledTokenImages setObject:tiledImages forKey:tokenImagePath];
    }
    tokenId = [[coder decodeObjectForKey:@"tokenId"] retain];
    origin = [coder decodeCGPointForKey:@"tokenOrigin"];
    originLock = [[NSObject alloc] init];
    coordPoint = [coder decodeCGPointForKey:@"tokenCoordinate"];
    self.protocolId = [coder decodeObjectForKey:@"protocolId"];
    return self;
}

@end
